package com.googlecode.gwt_control.client.form;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Olafur Gauti Gudmundsson
 */
public class FieldPanel extends Composite {

    private final Panel container;
    private final List<FieldChangeListener> fieldChangeListeners;
    private final List<FieldSection> sections;

    public FieldPanel() {
        this.container = new FlowPanel();
        container.setStyleName("fieldPanel");
        this.fieldChangeListeners = new ArrayList<FieldChangeListener>();
        this.sections = new ArrayList<FieldSection>();

        // add a listener that performs validation whenever a field changes
        fieldChangeListeners.add(new FieldChangeListener() {
            public void onChange(Field field) {
                field.validate();
            }
        });

        initWidget(container);
    }

    public Field findField( String id ) {
        for ( FieldSection section : sections ) {
            Field field = section.findField(id);
            if ( field != null ) {
                return field;
            }
        }
        return null;
    }

    public FieldSection addSection( String title ) {
        return addSection(title, null);
    }

    public FieldSection addSection( String title, String description ) {
        FieldSection section = new FieldSection(title, description, this);
        sections.add(section);
        container.add(section);
        return section;
    }

    public void addFieldChangeListener( FieldChangeListener listener ) {
        fieldChangeListeners.add(listener);
    }

    public List<FieldChangeListener> getFieldChangeListeners() {
        return fieldChangeListeners;
    }

    public boolean isValid() {
        boolean valid = true;
        List<Field> fields = new ArrayList<Field>();
        for ( FieldSection section : sections ) {
            fields.addAll(section.getFields());
        }
        for ( Field field : fields ) {
            if ( !field.validate() ) {
                valid = false;
            }
        }
        return valid;
    }

}
